#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os

def find_thrift_files(basedir):
    res = []
    res_shared = []
    for file in os.listdir(basedir):
        file = os.path.join(basedir, file)
        if file.endswith('.thrift') and os.path.isfile(file):
            if file.endswith('Shared.thrift'):
                res_shared.append(file)
            else:
                res.append(file)
    return res_shared + res

gen_languages =  (('py', 'gen_py'),
                  ('java', 'gen-java'),
                   )

def gen_thrifts(basedir, thrift_files):
    assert(os.path.isdir(basedir))
    # 生成目录
    for _, gen_dir in gen_languages:
        gen_dir = os.path.join(basedir, gen_dir)
        if not os.path.isdir(gen_dir):
            os.makedirs(gen_dir)
    for file in thrift_files:
        for gen_type, gen_dir in gen_languages:
            command = 'thrift -out %s -gen %s %s' % (gen_dir, gen_type, file)
            print(command)
            os.system(command)

if __name__ == '__main__':
    basedir = os.path.abspath(os.path.dirname(__file__))
    thrift_files = find_thrift_files(basedir)
    gen_thrifts(basedir, thrift_files)
    print('生成完成')
    